<template>
  <a-modal
    title="设置权限"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-tree
        checkable
        :defaultExpandAll="true"
        v-model="checkedKeys"
        :checkStrictly="true"
        :treeData="treeData"
      />
    </a-spin>
    <template slot="footer" >
      <a-button key="cancel" @click="handleCancel">取消</a-button>
      <a-button key="forward" :loading="confirmLoading" type="primary" @click="handleOk">保存</a-button>
    </template>
  </a-modal>

</template>

<script>
import { fetchList } from '@api/sys/perm'
import { treeDataTranslate } from '@/utils/util'
import { roleMenuIds, saveRoleMenu } from '@api/sys/role'
export default {
  name: 'RolePermModal',
  data () {
    return {
      confirmLoading: false,
      visible: false,
      treeData: [],
      checkedKeys: [],
      autoExpandParent: true,
      roleId: ''
    }
  },
  methods: {
    init (record) {
      this.visible = true
      this.confirmLoading = true
      this.roleId = record.id
      fetchList().then(res => {
        this.treeData = treeDataTranslate(res.data, 'id', 'name')
        this.confirmLoading = false
      })
      this.$nextTick(() => {
        roleMenuIds(record.id).then(res => {
          this.checkedKeys = res.data
        })
      })
    },
    handleCancel () {
      this.visible = false
    },
    handleOk () {
      this.confirmLoading = true
      if (this.checkedKeys.checked && this.checkedKeys.checked.length > 0) {
        saveRoleMenu(this.checkedKeys.checked, this.roleId).then(res => {
          setTimeout(() => {
            this.confirmLoading = false
            this.visible = false
          }, 1500)
        }).catch(err => {
          this.$message.error(err.msg)
        })
      } else {
        setTimeout(() => {
          this.confirmLoading = false
          this.visible = false
        }, 1500)
      }
    }
  }
}
</script>

<style scoped>

</style>
